package maldade.persistence.service;

import maldade.persistence.exception.RollbackException;
import maldade.persistence.exception.TransactionException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Persistence service.
 * 
 * @author rNojiri
 */
public class PersistenceService
{
	private SessionFactory sessionFactory;

	/**
	 * Sets the Session Factory.
	 * 
	 * @param sessionFactory
	 */
	public PersistenceService(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Starts a transaction.
	 * 
	 * @throws TransactionException
	 */
	public void beginTransaction() throws TransactionException
	{
		try
		{
			sessionFactory.getCurrentSession().beginTransaction();
		}
		catch (RuntimeException e)
		{
			throw new TransactionException(e);
		}
	}

	/**
	 * Commits the transaction.
	 * 
	 * @throws TransactionException
	 */
	public void commit() throws TransactionException
	{
		try
		{
			Transaction tx = sessionFactory.getCurrentSession().getTransaction();
			
			if (!tx.wasCommitted() && !tx.wasRolledBack())
			{
				tx.commit();
			}
		}
		catch (RuntimeException e)
		{
			throw new TransactionException(e);
		}
	}

	/**
	 * Rolls back the transaction.
	 * 
	 * @throws TransactionException
	 */
	public void rollback()
	{
		try
		{
			Transaction tx = sessionFactory.getCurrentSession().getTransaction();
			
			if (!tx.wasCommitted() && !tx.wasRolledBack())
			{
				tx.rollback();
			}
		}
		catch (RuntimeException e)
		{
			throw new RollbackException(e);
		}
	}
	
	/**
	 * Returns the session.
	 * 
	 * @return Session
	 */
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
}
